<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { API_CONFIG } from '../config/api'

const route = useRoute()
const router = useRouter()

interface User {
  id: number
  name: string
  type: number
  follow_num: number
  follower_num: number
  post_num: number
}

interface Post {
  id: number
  title: string
  content: string
  summary: string
  like_num: number
  created_at: string
}

interface FollowingUser {
  id: number
  name: string
  type: number
  follow_num: number
  follower_num: number
  post_num: number
}

interface FollowingData {
  total: number
  pages: number
  current_page: number
  following: FollowingUser[]
}

const user = ref<User | null>(null)
const posts = ref<Post[]>([])
const following = ref<FollowingUser[]>([])
const loading = ref(true)
const activeTab = ref('posts')
const postsLoading = ref(false)
const followingLoading = ref(false)
const postsPage = ref(1)
const followingPage = ref(1)
const postsTotal = ref(0)
const followingTotal = ref(0)
const currentUserId = ref<number | null>(null)

// 判断是否在查看其他用户的资料
const isOtherUser = computed(() => {
  const currentUser = JSON.parse(localStorage.getItem('user') || '{}')
  return currentUserId.value !== currentUser.id
})

// 检查登录状态
const checkLoginStatus = (): boolean => {
  const token = localStorage.getItem('token')
  return !!token
}

// 获取请求头
const getHeaders = (): Record<string, string> => {
  const headers: Record<string, string> = {
    'Content-Type': 'application/json'
  }
  
  const token = localStorage.getItem('token')
  if (token) {
    headers['Authorization'] = `Bearer ${token}`
  }
  
  return headers
}

// 处理API响应
const handleApiResponse = async (response: Response) => {
  if (!response.ok) {
    throw new Error(`HTTP Error: ${response.status} ${response.statusText}`)
  }
  
  const data = await response.json()
  
  if (data.code !== 200) {
    throw new Error(data.message || '请求失败')
  }
  
  return data.data
}

const fetchUserInfo = async () => {
  if (!currentUserId.value) return
  
  loading.value = true
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/users/${currentUserId.value}`, {
      method: 'GET',
      headers: getHeaders()
    })
    
    const userData = await handleApiResponse(response)
    user.value = userData
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '获取用户信息失败')
  } finally {
    loading.value = false
  }
}

const fetchUserPosts = async () => {
  if (!currentUserId.value) return
  
  postsLoading.value = true
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/users/${currentUserId.value}/posts?page=${postsPage.value}&size=10`, {
      method: 'GET',
      headers: getHeaders()
    })
    
    const postsData = await handleApiResponse(response)
    posts.value = postsData.posts || []
    postsTotal.value = postsData.total || 0
  } catch (error) {
    console.error('获取用户帖子失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '获取用户帖子失败')
  } finally {
    postsLoading.value = false
  }
}

const fetchFollowing = async () => {
  if (!currentUserId.value) return
  
  followingLoading.value = true
  try {
    const response = await fetch(`${API_CONFIG.BASE_URL}/users/${currentUserId.value}/following?page=${followingPage.value}&size=20`, {
      method: 'GET',
      headers: getHeaders()
    })
    
    const followingData: FollowingData = await handleApiResponse(response)
    following.value = followingData.following || []
    followingTotal.value = followingData.total || 0
  } catch (error) {
    console.error('获取关注列表失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '获取关注列表失败')
  } finally {
    followingLoading.value = false
  }
}

const handleFollow = async (userId: number) => {
  try {
    const currentUser = JSON.parse(localStorage.getItem('user') || '{}')
    const followerId = currentUser.id
    
    if (!followerId) {
      ElMessage.error('用户信息不完整')
      return
    }
    
    const response = await fetch(`${API_CONFIG.BASE_URL}/users/${userId}/follow`, {
      method: 'POST',
      headers: getHeaders(),
      body: JSON.stringify({
        user_id: userId,
        follower_id: followerId
      })
    })
    
    await handleApiResponse(response)
    ElMessage.success('关注成功')
    
    // 刷新关注列表
    await fetchFollowing()
  } catch (error) {
    console.error('关注失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '关注失败')
  }
}

const handleUnfollow = async (userId: number) => {
  try {
    const currentUser = JSON.parse(localStorage.getItem('user') || '{}')
    const followerId = currentUser.id
    
    if (!followerId) {
      ElMessage.error('用户信息不完整')
      return
    }
    
    // 注意：这里假设取消关注也是使用同一个接口，实际可能需要DELETE方法或不同的参数
    // 根据实际后端实现调整
    const response = await fetch(`${API_CONFIG.BASE_URL}/users/${userId}/follow`, {
      method: 'DELETE', // 或者POST with action parameter
      headers: getHeaders(),
      body: JSON.stringify({
        user_id: userId,
        follower_id: followerId
      })
    })
    
    await handleApiResponse(response)
    ElMessage.success('取消关注成功')
    
    // 刷新关注列表
    await fetchFollowing()
  } catch (error) {
    console.error('取消关注失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '取消关注失败')
  }
}

const goToPost = (id: number) => {
  router.push(`/posts/${id}`)
}

const goToUserProfile = (userId: number) => {
  router.push(`/profile?userId=${userId}`)
}

onMounted(() => {
  // 检查登录状态
  if (!checkLoginStatus()) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  // 获取用户ID（从路由参数或当前登录用户）
  const userIdParam = route.query.userId as string
  if (userIdParam) {
    currentUserId.value = parseInt(userIdParam)
  } else {
    // 如果没有指定用户ID，显示当前登录用户的信息
    const currentUser = JSON.parse(localStorage.getItem('user') || '{}')
    if (currentUser.id) {
      currentUserId.value = currentUser.id
    } else {
      ElMessage.error('无法获取用户信息')
      router.push('/login')
      return
    }
  }
  
  // 获取数据
  fetchUserInfo()
  fetchUserPosts()
  fetchFollowing()
})
</script>

<template>
  <div class="profile">
    <div v-if="loading" class="loading-container">
      <el-card>
        <el-skeleton :rows="5" animated />
      </el-card>
    </div>
    
    <div v-else-if="user" class="profile-container">
      <!-- 用户信息卡片 -->
      <el-card class="user-info-card">
        <div class="user-header">
          <el-avatar :size="80" class="user-avatar">
            {{ user.name.charAt(0) }}
          </el-avatar>
          <div class="user-details">
            <h1 class="user-name">{{ user.name }}</h1>
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-number">{{ user.post_num }}</span>
                <span class="stat-label">帖子</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ user.follow_num }}</span>
                <span class="stat-label">关注</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ user.follower_num }}</span>
                <span class="stat-label">粉丝</span>
              </div>
            </div>
            <div class="user-type">
              <el-tag :type="user.type === 2 ? 'danger' : user.type === 1 ? 'warning' : 'info'">
                {{ user.type === 2 ? '管理员' : user.type === 1 ? '版主' : '普通用户' }}
              </el-tag>
            </div>
          </div>
          <div class="user-actions">
            <!-- 只有在查看其他用户时才显示关注按钮 -->
            <el-button 
              v-if="isOtherUser" 
              type="primary" 
              @click="handleFollow(user.id)"
            >
              <el-icon><Plus /></el-icon>
              关注
            </el-button>
            
            <!-- 只有在查看自己时才显示发布帖子按钮 -->
            <el-button 
              v-if="!isOtherUser" 
              type="primary" 
              @click="router.push('/create-post')"
            >
              <el-icon><Edit /></el-icon>
              发布帖子
            </el-button>
            
            <el-button @click="router.push('/posts')">
              <el-icon><Back /></el-icon>
              返回列表
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 标签页 -->
      <el-card class="tabs-card">
        <el-tabs v-model="activeTab" @tab-click="(tab) => {
          if (tab.props.name === 'posts') fetchUserPosts()
          if (tab.props.name === 'following') fetchFollowing()
        }">
          <el-tab-pane label="发布的帖子" name="posts">
            <div v-if="postsLoading" class="loading-content">
              <el-skeleton :rows="3" animated />
            </div>
            <div v-else class="posts-list">
              <div v-if="posts.length === 0" class="empty-content">
                <el-empty description="还没有发布过帖子" />
              </div>
              <div v-else>
                <el-card 
                  v-for="post in posts" 
                  :key="post.id" 
                  class="post-item"
                  @click="goToPost(post.id)"
                >
                  <div class="post-content">
                    <h3 class="post-title">{{ post.title || post.summary }}</h3>
                    <div class="post-stats">
                      <span class="post-likes">
                        <el-icon><ThumbsUp /></el-icon>
                        {{ post.like_num }} 点赞
                      </span>
                    </div>
                  </div>
                </el-card>
                
                <!-- 分页 -->
                <div class="pagination-container">
                  <el-pagination
                    v-model:current-page="postsPage"
                    :page-size="10"
                    :total="postsTotal"
                    layout="prev, pager, next"
                    @current-change="fetchUserPosts"
                  />
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="关注列表" name="following">
            <div v-if="followingLoading" class="loading-content">
              <el-skeleton :rows="3" animated />
            </div>
            <div v-else class="following-list">
              <div v-if="following.length === 0" class="empty-content">
                <el-empty description="还没有关注任何用户" />
              </div>
              <div v-else>
                <el-card 
                  v-for="followUser in following" 
                  :key="followUser.id" 
                  class="following-item"
                >
                  <div class="following-content">
                    <div class="following-user">
                      <el-avatar :size="50" class="following-avatar">
                        {{ followUser.name.charAt(0) }}
                      </el-avatar>
                      <div class="following-details">
                        <h4 class="following-name" @click="goToUserProfile(followUser.id)">
                          {{ followUser.name }}
                        </h4>
                        <div class="following-stats">
                          <span>{{ followUser.post_num }} 帖子</span>
                          <span>{{ followUser.follower_num }} 粉丝</span>
                        </div>
                        <div class="following-type">
                          <el-tag size="small" :type="followUser.type === 1 ? 'warning' : 'info'">
                            {{ followUser.type === 1 ? '版主' : '普通用户' }}
                          </el-tag>
                        </div>
                      </div>
                    </div>
                    <div class="following-actions">
                      <el-button 
                        type="danger" 
                        size="small"
                        @click="handleUnfollow(followUser.id)"
                      >
                        取消关注
                      </el-button>
                    </div>
                  </div>
                </el-card>
                
                <!-- 分页 -->
                <div class="pagination-container">
                  <el-pagination
                    v-model:current-page="followingPage"
                    :page-size="20"
                    :total="followingTotal"
                    layout="prev, pager, next"
                    @current-change="fetchFollowing"
                  />
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    
    <div v-else class="error-container">
      <el-result
        icon="error"
        title="用户不存在"
        sub-title="抱歉，您访问的用户不存在"
      >
        <template #extra>
          <el-button type="primary" @click="router.push('/posts')">
            返回帖子列表
          </el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<style scoped>
.profile {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 10px;
}

.loading-container {
  margin-bottom: 20px;
}

.profile-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.user-info-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.user-header {
  display: flex;
  align-items: center;
  gap: 30px;
  flex-wrap: wrap;
}

.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: bold;
  font-size: 2em;
}

.user-details {
  flex: 1;
}

.user-name {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 2em;
  font-weight: bold;
}

.user-stats {
  display: flex;
  gap: 30px;
  margin-bottom: 15px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.stat-number {
  font-size: 1.5em;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  color: #666;
  font-size: 0.9em;
}

.user-type {
  margin-bottom: 15px;
}

.user-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.tabs-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.loading-content {
  padding: 20px 0;
}

.posts-list,
.following-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.empty-content {
  padding: 40px 0;
}

.post-item {
  cursor: pointer;
  transition: all 0.3s ease;
}

.post-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.post-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-title {
  margin: 0;
  color: #333;
  font-size: 1.1em;
  font-weight: 600;
}

.post-stats {
  color: #666;
  font-size: 0.9em;
}

.post-likes {
  display: flex;
  align-items: center;
  gap: 5px;
}

.following-item {
  margin-bottom: 15px;
}

.following-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.following-user {
  display: flex;
  align-items: center;
  gap: 15px;
}

.following-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: bold;
}

.following-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.following-name {
  margin: 0;
  color: #409eff;
  cursor: pointer;
  font-size: 1.1em;
  font-weight: 600;
}

.following-name:hover {
  text-decoration: underline;
}

.following-stats {
  display: flex;
  gap: 15px;
  color: #666;
  font-size: 0.9em;
}

.following-type {
  margin-top: 5px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.error-container {
  margin-top: 50px;
}

@media (max-width: 768px) {
  .profile {
    padding: 0 10px;
  }
  
  .user-header {
    flex-direction: column;
    text-align: center;
  }
  
  .user-stats {
    justify-content: center;
  }
  
  .user-actions {
    width: 100%;
    justify-content: center;
  }
  
  .following-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .following-actions {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
  
  .user-name {
    font-size: 1.8em;
  }
  
  .user-avatar {
    font-size: 1.5em;
  }
}

@media (max-width: 480px) {
  .profile {
    padding: 0 5px;
  }
  
  .user-name {
    font-size: 1.5em;
  }
  
  .user-stats {
    gap: 20px;
  }
  
  .stat-number {
    font-size: 1.3em;
  }
}
</style>